(function() {

    var AudioManager = function() {
        this.readyFuncs = [];
        this.audio = {};
        this.isIos = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    }

    AudioManager.prototype.load = function(sounds) {
        var self = this;
            loaded = 0;
        sounds.forEach(function(sound) {
            var audio = document.createElement('audio');
            if (self.isIos) {
                self.audio[sound.id] = audio;
                if ((++loaded) == sounds.length) {
                    self.readyFuncs.forEach(function(f) {
                        f();
                    })
                }
            } else {
                audio.addEventListener('canplay', function() {
                    self.audio[sound.id] = audio;
                    if ((++loaded) == sounds.length) {
                        self.readyFuncs.forEach(function(f) {
                            f();
                        })
                    }
                });
            }
            audio.src = sound.src;
        });
        // createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin]);
        // createjs.Sound.addEventListener("fileload", function() {
        //     if ((++loaded) == sounds.length) {
        //         self.readyFuncs.forEach(function(f) {
        //             f();
        //         })
        //     };
        // });
        // sounds.forEach(function(sound) {
        //     createjs.Sound.registerSound(sound.src, sound.id, sound.data);
        // });
    }

    AudioManager.prototype.ready = function() {
        for (var i=0, l=arguments.length; i < l; i++) {
            this.readyFuncs.push(arguments[i]);
        }
    }

    AudioManager.prototype.play = function(id, option, callback) {
        for(var key in option) {
            this.audio[id][key] = option[key];
        }
        // console.log(this.audio[id].muted);
        // }
        if (!this.audio[id].ended) {
            try {
                this.audio[id].currentTime = 0;
            } catch(e) {

            }
        // alert(this.audio[id].currentTime)
        }
        this.audio[id].play();
        // this.audio[id].onended = function() {
        //     alert('haha')
        // });
        // option = option || {};
        // var instance = createjs.Sound.createInstance(id);
        // instance.play(option);
        // instance.on('succeeded', function() {
        //     alert('haha')
        // });
        // return instance;
    }

    AudioManager.prototype.stop = function(id) {
        this.audio[id].pause();
    }

    AudioManager.prototype.resume = function(id) {
        this.audio[id].play();
    }

    AudioManager.prototype.reload = function(id) {
        this.audio[id].load();
    }

    AudioManager.prototype.onended = function(id, fun) {
        this.audio[id].addEventListener('ended', fun, false);
    }

    window.AudioManager = AudioManager;

})();